package com.ruoyi.project.tool.websocket.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.config.SocketEndpointConfigure;
import com.ruoyi.project.system.face.service.IFaceService;
import com.ruoyi.project.tool.swagger.domain.IFace;

@ServerEndpoint(value = "/socketServer/{gateId}", configurator = SocketEndpointConfigure.class)
@Component
public class SocketServer {

    private Session session;
    public static Map<String, Session> sessionPool = new HashMap<String, Session>();
    private static Map<String, String> sessionIds = new HashMap<String, String>();
    @Autowired
    private IFaceService faceService;

    /**
     * 用户连接时触发
     * 
     * @param session
     * @param userid
     */
    @OnOpen
    public void open(Session session, @PathParam(value = "gateId") String gateId) {
        this.session = session;
        if (sessionPool.get(gateId) != null) {
            Session s = sessionPool.get(gateId);
            sessionPool.remove(gateId);
            sessionIds.remove(s.getId());
        }
        sessionPool.put(gateId, session);
        sessionIds.put(session.getId(), gateId);
    }

    /**
     * 收到信息时触发
     * 
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        // sendMessage(sessionIds.get(session.getId())+"<--"+message,"niezhiliang9595");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("type", Constants.FACE_LIST);
        List<IFace> list = new ArrayList<IFace>();
        String jsonStr = null;
        if (StringUtils.isNotBlank(message)) {
            JSONObject jsonObject = JSONObject.parseObject(message);
            Integer deptId = null;
            Long latestTime = null;
            if (jsonObject.get("deptId") != null) {
                deptId = (Integer) jsonObject.get("deptId");
            }
            if (jsonObject.get("version") != null) {
                latestTime = (Long) jsonObject.get("version");
            }
            int num = faceService.queryFaceTotal(deptId, latestTime);
            if (num <= Constants.PAGESIZE) {// 非分页查询
                list = faceService.queryFaceList(deptId, latestTime);
                map.put("data", list);
                jsonStr = JSON.toJSONString(map);
                sendMessage(jsonStr, sessionIds.get(session.getId()));
            } else {// 分页查询
                int pageTotal = (num + Constants.PAGESIZE - 1) / Constants.PAGESIZE;
                for (int i = 1; i <= pageTotal; i++) {
                    PageHelper.startPage(i, Constants.PAGESIZE, false);
                    list = faceService.queryFaceList(deptId, latestTime);
                    map.put("data", list);
                    jsonStr = JSON.toJSONString(map);
                    sendMessage(jsonStr, sessionIds.get(session.getId()));
                }
            }
        } else {
            map.put("data", list);
            jsonStr = JSON.toJSONString(map);
            sendMessage(jsonStr, sessionIds.get(session.getId()));
        }

    }

    /**
     * 连接关闭触发
     */
    @OnClose
    public void onClose() {
        sessionPool.remove(sessionIds.get(session.getId()));
        sessionIds.remove(session.getId());
    }

    /**
     * 发生错误时触发
     * 
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 信息发送的方法
     * 
     * @param message
     * @param userId
     */
    public static void sendMessage(String message, String gateId) {
        Session s = sessionPool.get(gateId);
        if (s != null) {
            try {
                s.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取当前连接数
     * 
     * @return
     */
    public static int getOnlineNum() {
        if (sessionIds.values().contains("niezhiliang9595")) {

            return sessionPool.size() - 1;
        }
        return sessionPool.size();
    }

    /**
     * 获取在线用户名以逗号隔开
     * 
     * @return
     */
    public static String getOnlineUsers() {
        StringBuffer users = new StringBuffer();
        for (String key : sessionIds.keySet()) {// niezhiliang9595是服务端自己的连接，不能算在线人数
            if (!"niezhiliang9595".equals(sessionIds.get(key))) {
                users.append(sessionIds.get(key) + ",");
            }
        }
        return users.toString();
    }

    /**
     * 信息群发
     * 
     * @param msg
     */
    public static void sendAll(String msg) {
        for (String key : sessionIds.keySet()) {
            if (!"niezhiliang9595".equals(sessionIds.get(key))) {
                sendMessage(msg, sessionIds.get(key));
            }
        }
    }

    /**
     * 多个人发送给指定的几个用户
     * 
     * @param msg
     * @param persons 用户s
     */

    public static void SendMany(String msg, String[] persons) {
        for (String userid : persons) {
            sendMessage(msg, userid);
        }

    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap();
        map.put("deptId", 101);
        map.put("latestTime", "2018-12-15 15:09:54");
        System.out.println(JSON.toJSONString(map));
        String str = "2018-12-17 09:29:16";
        System.out.println(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, str).getTime());
    }
}
